<?php

namespace App\Imports;

use App\Models\Score;
use App\Models\Student;
use App\Models\Subject;
use Carbon\Carbon;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithStartRow;

class ScoreImport implements ToModel,WithStartRow
{
    public function startRow(): int
    {
        return 2;
    }
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
       $student_id =  $this->getStudentId($row[0],$row[1],$row[2],$row[3]);
       $subject_id = $this->getSubjectId($row[5]);
       $score = new Score([
            'test_date' =>  $this->transformDate($row[6]),
            'score' => $row[4],
            'yk_number'=>$row[7],
            'yk_percent'=>$row[8],
            'grade'=>$row[9],
        ]);

       $score->student()->associate($student_id);
       $score->subject()->associate($subject_id);
        return $score;
    }

    public function getStudentId($no,$name,$group,$class)
    {
        $student = Student::where('no',$no)->first();
        if ($student) {
            return $student->id;
        }else{
            $student = Student::create([
                'no' => $no,
                'name' => $name,
                'group_name' => $group,
                'class_name' => $class,
            ]);
            return $student->id;
        }
    }

    private function getSubjectId($subject_name)
    {
        $subject = Subject::where('name',$subject_name)->first();
        if ($subject){
            return $subject->id;
        }else{
            $subject = Subject::create([
                'name' => $subject_name,
            ]);
            return $subject->id;
        }

    }

    private function transformDate($date)
    {
        try {
            return Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($date))->toDateTimeString();
        } catch (\ErrorException $e) {
            return Carbon::createFromFormat('Y-m-d H:i:s', $date)->toDateTimeString();
        }
    }
}
